<template>
  <div>
    <!--热门标签-->
    <div class="ms-3">
      <label>热门标签:</label>
      <el-Tag
        v-for="(tag, index) in hotTags"
        :key="index"
        :type="tagColor[index]"
        class="ms-3"
        @click="selHotTags(tag.tagName)"
      >
        {{ tag.tagName }}
      </el-Tag>
    </div>

    <!--选中标签-->
    <div class="ms-3 my-3">
      <label>选中标签:</label>
      <el-Tag
        v-for="(tag, index) in selectTags"
        :key="index"
        :type="tagColor[index]"
        class="ms-3"
        closable
        @close="delSelctTags(index)"
      >
        {{ tag }}
      </el-Tag>
      <el-input 
        class="ms-3"
        v-model="newTags"
        style="width: 5rem" 
        size="small"
        @keyup.enter="addnewTag"
       >
       </el-input>
    </div>
  </div>
</template>

<script>
export default {
  name: "NoteTag",
  emits: ["getTags"], //emits数组用于自定义事件，定义getTags事件，用于传递数据给父组件
  data() {
    return {
      hotTags: [
        { tagName: "前端" },
        { tagName: "VUE" },
        { tagName: "JS" },
        { tagName: "CSS" },
        { tagName: "Bootstrap" },
      ],
      //标签颜色
      tagColor: ["", "success", "info", "warning", "danger"],
      //选中标签
      selectTags: [],
      //新增的标签
      newTags: null,
    };
  },
  methods: {
    //热门标签的点击事件，所触发的函数
    selHotTags(tagName) {
      this.selectTags.push(tagName);
    },
    //删除选中的标签
    delSelctTags(index) {
      this.selectTags.splice(index, 1);
    },
    //当按下回车触发的函数
    addNewTag(){
      this.selectTags.push(this.newTags);
      this.newTags = null;
    }
  },
  watch: {
    selectTags: {
      //每当selectTags数组元素变化时，都会触发hanler()函数
      handler() {
        //把selectTag数组通过自定义事件getTags,传给NoteAdd组件
        this.$emit("getTags", this.selectTags);
      },
      deep: true, //该属性表示深入数组，监听数组元素的增加和删除
    },
    //由于detailTags数组和selectTags数组的数据格式不一样，需要转换
    //detailTags = [{ "tagId": 4,"tagName":"vue"}]
    //selectTags = [ "vue"]
    detailTags: {
      handler() {
        if(this.detailTags != undefined) {
          //使用forEach循环，遍历detailTags中的元素
          this.detailTags.forEach((tag) => {
            //从每个元素中取出tagName，装入selectTags变量
            this.selectTags.push(tag.tagName);          
          });
        }
      },
      deep:true,//该属性表示深入数组，监听数组元素的增加和删除
    },
  },
};
</script>

